(function($){    
    /**
     * 工具条.
     * @constructor 
     * @param {Selector} selector
     * @param {Object} config
     */
    var _Toolbar = function(selector, config){
        var _this = this, 
            defaultConfig = {};
        
        _this.config = $.extend({}, defaultConfig, config);            
        _this.$wrapper = $(selector).addClass('toolbar');
        
        Observable.enable(this);
                
        if(_this.config['cls']){
            _this.$wrapper.addClass(_this.config['cls']);
        }        
        _this.$wrapper.style(_this.config['theme']);
        _this.$wrapper.style(_this.config['style']);
        
        _this.$wrapper.find('>*').each(function(){
            $(this).addClass('toolbarItem');
        });
        
        _this.$wrapper.delegate('>.toolbarItem', 'click', function(e){            
            _this.fire('click', $(this), _this);
            if($(this).attr('tbi-type') == 'checkbox'){
            	return true;
            } else {
            	return false;
            }
        });
          
        Observable.regEvent(this, _this.config, function(){
            this.fire('init', this);
        });
    };
    
    //-------------------------------------------------------------------
     
    /**
     * 通用添加工具条项. 
     */
    _Toolbar.prototype.addItem = function(toolbarItemHtml, itemCfg, cb){        
        //兼容addItem(toolbarItemHtml, cb)
        if(Type.isFunction(itemCfg)){
           cb = itemCfg;
           itemCfg = {}; 
        }
        
        if(!Type.isJQuery(toolbarItemHtml) && !Type.isString(toolbarItemHtml)){
            var toolbarItemObject = toolbarItemHtml;
            toolbarItemHtml = toolbarItemObject.$wrapper;
        }
        
        var $toolbarItem = $(toolbarItemHtml).addClass('toolbarItem');
        
        //toolbar item 分组.
        if(itemCfg['group']){
            $toolbarItem.attr('tbi-group', itemCfg['group']);
        }
        
        $toolbarItem.style(itemCfg['style']);
        
        //向右对齐.
        if(itemCfg['align'] === 'right'){
            $toolbarItem.addClass('right');
        }
        
        var newItemPos = itemCfg['position'];
        if(newItemPos == 'before'){
            this.$wrapper.prepend($toolbarItem);
        } else {
            this.$wrapper.append($toolbarItem);
        }
        
        if(cb){
            cb.call(this, $toolbarItem);
        }
        return this;
    };
        
    /**
     * 获取工具条项.
     * @param tbiID {String} 工具条项ID.
     * @return {jQuery} 工具条项jQuery对象. 
     */
    _Toolbar.prototype.getItem = function(tbiID){
        var $tbiItem = this.$wrapper.find('.toolbarItem[tbi-id={0}]'.format(tbiID));
        return $tbiItem.isEmpty() ? null : $tbiItem;
    };
    
    //---------------------------------------------------------------------------------------------------------------------
    
    /**
     * 添加工具条按钮项.
     * @param btnCfg {Options} 按钮配置.
     * @return this; 
     */
    _Toolbar.prototype.addButton = function(btnCfg, cb){
        var $button = $([
            '<span tbi-id="{id}" tbi-type="button" title="{tooltip}">',
                '<button class="toolbarButton {cls}">',
                    '{text}',
                '</button>',
            '</span>'
        ].join('').format(btnCfg) );
        
        if(btnCfg['toggle'] === true){
            
        }
        
        if(btnCfg.onClick){
            $button.find('button').bind('click', $.proxy(btnCfg.onClick, $button, btnCfg) );
        }
        if(btnCfg.onMouseOver){
            $button.find('button').bind('mouseover', $.proxy(btnCfg.onMouseOver, $button, btnCfg) );
        }
        return this.addItem($button, btnCfg, cb);
    };
    
    /**
     * 添加图片按钮.
     * @param {Options} btnCfg
     * @param {Function} cb
     * @return this.
     */
    _Toolbar.prototype.addImageButton = function(btnCfg, cb){
        btnCfg['text'] = '<img src="{src}" title="{tooltip}" />'.format({
            src : btnCfg['image'],
            tooltip : btnCfg['tooltip'] || btnCfg['label'] || ''
        });
        
        var $label = this._genLabel(btnCfg);
        if($label){
            if(btnCfg['isShowLabel'] !== false){
                var labelPos = btnCfg['labelPos'],
                    labelHtml = $label.get(0).outerHTML;
                if(labelPos == 'left' || labelPos == 'top'){
                    btnCfg['text'] = labelHtml + btnCfg['text'];
                } else {
                    btnCfg['text'] += labelHtml;
                }    
            }
        }
        return this.addButton(btnCfg, cb);
    };
    
    _Toolbar.prototype._genLabel = function(labelConfig){
        if(labelConfig['isShowLabel'] !== false){
            var $label = $('<label class="tbLabel {labelPos}">{label}</label>'.format({
                labelPos : labelConfig['labelPos'],
                label : labelConfig['label'] || ''
            }));
            $label.style(labelConfig['labelStyle']);
            return $label;
        }
    };
    
    //--------------------------------------------------------------------------------------------------------------------------
    
    /**
     * 添加搜索框. 
     */
    _Toolbar.prototype.addSearchBox = function(searchBoxCfg, cb){
        var $searchBox = $('<span tbi-id="{id}" ></span>'.format(searchBoxCfg));
        //顶部搜索条.
        $searchBox.searchable($.extend({}, searchBoxCfg));        
        return this.addItem($searchBox, searchBoxCfg, cb);
    };
    
    /**
     * 添加单行输入框. 
     */
    _Toolbar.prototype.addInputBox = function(config, cb){
        var $wrapper = $(tmpl([
            '<div class="inlineBlock">',
                '<input name="<%=o.inputBoxConfig.id%>" class="toolbarInput"/>',
            '</div>'
        ], config));    
        $wrapper.find('.toolbarInput').style(config.inputBoxConfig['style']);    
        var $label = this._genLabel(config);
        if($label){
            $wrapper.append($label);    
        }        
        return this.addItem($wrapper, config, cb);
    };
    
    /**
     * 添加下拉框. 
     */
    _Toolbar.prototype.addSelectBox = function(config, cb){
        var $wrapper = $('<div class="inlineBlock"></div>');
        var $label = this._genLabel(config);
        if($label){
            $wrapper.append($label);    
        }
        var $selectBox = $('<span tbi-id="{id}" ></span>'.format(config));
        var selectBox = $selectBox.selectBox($.extend({}, config['selectBoxConfig']));        
        $wrapper.append(selectBox.$wrapper);
        return this.addItem($wrapper, config, cb);
    };
    
    /**
     * 添加树节点选择控件. 
     */
    _Toolbar.prototype.addTreeNodeSelector = function(config, cb){
        var $wrapper = $('<div class="inlineBlock"></div>');
        var $label = this._genLabel(config);
        if($label){
            $wrapper.append($label);    
        }
        
        var $treeNodeSelector = $([
            '<span tbi-id="{id}" name="{id}" class="formField">',
                '<input class="toolbarInput exceptFromForm"/>',
            '</span>'
        ].join('').format(config['treeNodeSelectorConfig']));   
             
        var treeNodeSelector = $treeNodeSelector.find('.toolbarInput').treeNodeSelector(
            $.extend({}, config['treeNodeSelectorConfig'])
        ).data('treeNodeSelector');
        treeNodeSelector.on('selectNode', function(nodeID, nodeText, nodeIcon, node) {});
                
        $wrapper.append($treeNodeSelector);
        return this.addItem($wrapper, config, cb);
    };
    
    /**
     * 添加功能性下拉菜单. 
     */
    _Toolbar.prototype.addDDActionMenu = function(itemCfg, cb){
        this['add' + itemCfg['itemType'].uppercaseFirstChar()](itemCfg, function($toolbarItem){
            $toolbarItem.ddActionMenu($.extend({}, itemCfg['ddActionMenuCfg']));
            cb && cb.call(this, $toolbarItem);
        });
    };
    
    //--------------------------------------------------------------------------------------------------------------------------
    
    /**
     * 添加复选框项. 
     * @param {Config} checkboxCfg
     * @param {Function} cb
     */
    _Toolbar.prototype.addCheckbox = function(checkboxCfg, cb){
        checkboxCfg['tick'] = Date.now();
        
        var checkboxContentTmp = [
            '<label for="{id|name}_{tick}" class="{labelCls}">{text|label}</label>',
        ];
        checkboxContentTmp[ checkboxCfg['labelPos'] == 'right' ? 'unshift' : 'push' ](
            '<input id="{id|name}_{tick}" type="checkbox" class="{cls}" name="{name|id}"/>'
        );
        
        var $checkboxItem = $([
            	'<span tbi-id="{id|name}" tbi-type="checkbox">',
            		checkboxContentTmp.join(''),
        		'</span>'
    		].join('').format(checkboxCfg)), 
    		
            $checkbox = $checkboxItem.find(':checkbox'); 
		
		$checkbox.change(function(){
			if(Type.isFunction(checkboxCfg['onChange'])){
				checkboxCfg['onChange']($(this).is(':checked'));
			}
		}).prop('checked', !!checkboxCfg['isChecked']);
		      
        return this.addItem($checkboxItem, checkboxCfg, cb);
    };
    
    //--------------------------------------------------------------------------------------------------------------------------
    
    /**
     * 添加文本标签. 
     */
    _Toolbar.prototype.addLabel = function(labelCfg, cb){
        var $label = $('<span tbi-id="{id}" tbi-type="label"><label class="{cls}">{text}</label></span>'.format(labelCfg));        
        return this.addItem($label, labelCfg, cb);
    };
    
    _Toolbar.prototype.setLabel = function(labelID, text){
        var $label = this.getItem(labelID);
        if($label){
            $label.find('label').text(text);
        }
    };
    
    //--------------------------------------------------------------------------------------------------------------------------
    
    /**
     * 添加分隔条 
     */
    _Toolbar.prototype.addSep = function(sepCfg, cb){
        sepCfg = sepCfg || {};
        sepCfg.id = Date.now();
        var $sep = $('<span tbi-id="{id}" tbi-type="sep" class="sep"></span>'.format(sepCfg));        
        return this.addItem($sep, sepCfg, cb);
    };
        
    //-----------------------------------------------------------------------------------------------
    
    /**
     * 仅显示指定组的工具条项. 
     */
    _Toolbar.prototype.filterByGroup = function(groupName){
        var $tbis = this.$wrapper.find('.toolbarItem');
        $tbis.each(function(){
            var $tbi = $(this);
            var tbi_group = $tbi.attr('tbi-group');
            if(tbi_group && !(new RegExp('(^|,)' + groupName + '($|,)', 'gi')).test(tbi_group)){
                $tbi.hide();
            } else {
                $tbi.show();
            }
        });    
    };
    
    //------------------------------------------------------------------------------------------------
    
    _Toolbar.prototype.hideItem = function(itemID){
        this.$wrapper.find('span[tbi-id={0}]'.format(itemID)).hide();
    };
    
    _Toolbar.prototype.showItem = function(itemID){
        this.$wrapper.find('span[tbi-id={0}]'.format(itemID)).show();
    };
    
    //------------------------------------------------------------------------------------------------
    
    /**
     * 获取工具上表单元素的值. 
     * @param {Boolean} isBoolTo_01
     */
    _Toolbar.prototype.getValues = function(isBoolTo_01){
        return Object.shrink(ujs.browser.form.getValues(this.$wrapper, isBoolTo_01));
    };
    
    //------------------------------------------------------------------------------------------------
    
    //init interface.
    $.fn.toolbar = function(config){        
        this.each(function(){
            var toolbarObj = new _Toolbar(this, config);            
            $(this).data('toolbar', toolbarObj);
        });
        return this;
    };
})(jQuery);